<?php

/**
 * Contains a class to display /user/edit_event.php.
 *
 * PHP Version 5
 *
 * @category BuyLocal
 * @package  BuyLocal
 * @author   Kevin Fodness <kevin.fodness@gmail.com>
 * @author   Mike Pennisi <mpennisi@andrew.cmu.edu>
 * @author   Aaron Ryden <aryden@gmail.com>
 * @author   Spencer Hakim <hakims@rpi.edu>
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link     http://code.google.com/p/buylocalopensourcerensselaer/
 */

/** @uses getStateList To get an array of U.S. states. */
require_once 'function_getstatelist.php';
 
/** @uses valueOf For safe handling of arrays. */
require_once 'function_valueof.php';
 
/**
 * A class to display /user/edit_event.php.
 *
 * @category BuyLocal
 * @package  BuyLocal
 * @author   Kevin Fodness <kevin.fodness@gmail.com>
 * @author   Mike Pennisi <mpennisi@andrew.cmu.edu>
 * @author   Aaron Ryden <aryden@gmail.com>
 * @author   Spencer Hakim <hakims@rpi.edu>
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link     http://code.google.com/p/buylocalopensourcerensselaer/
 */ 
class PageEditevent extends Page
{
    /**
     * State variable for whether or not to update the event info.
     *
     * @access private
     * @var bool
     */
    private $_updateInfo;

    /**
     * State variable for whether or not to delete the event.
     *
     * @access private
     * @var bool
     */
    private $_delete;
    
    /**
     * The event which we are currently editing.
     *
     * @access private
     * @var bool
     */
    private $_event;

    /**
     * Contains the error text, if any, to display.
     *
     * @access public
     * @var string
     */
    public $error;
    
    /**
     * Constructor function.  Calls the parent constructor and sets the title.
     */
    public function __construct()
    {
        parent::__construct();
        if (valueOf($_GET, 'eventid') != '') {
            $this->_event = $this->db->getEventById(
                valueOf($_GET, 'eventid'), $this->user->zip->latitude,
                $this->user->zip->longitude, true
            );
        }

        if (count($_POST) > 0) {
            $this->_updateInfo = true;
        } else if (valueOf($_GET, 'action') == 'delete') {
            $this->_delete = true;
        }
        parent::setTitle('Edit event');
    }
    
    /**
     * Function to print an INPUT form field.
     *
     * @param string $id        The value to use for the id and name fields.
     * @param string $label     The string to insert between the <label> tags.
     * @param string $type      The type of the input field (text, password).
     * @param string $maxlength The maximum length for the input field.
     * @param string $value     The string to insert into the value attribute.
     *
     * @access private
     * @return null
     */
    private function _printFormField($id, $label, $type, $maxlength, $value)
    {
        $id        = encode($id);
        $label     = encode($label);
        $type      = encode($type);
        $maxlength = encode($maxlength);
        $value     = encode($value);
        
        echo '  <div>', "\n",
            '   <label for="', $id, '">', $label, ':</label>', "\n",
            '   <input id="', $id, '" name="', $id, '" type="', $type, '" ',
            'maxlength="', $maxlength, '" value="', encode($value), '" />', "\n",
            '  </div>', "\n";
    }
    
    /**
     * Function for printing the States dropdown box.
     *
     * @access private
     * @return string
     */
    private function _printStates()
    {
        $stateList = getStateList();
        $keys = array_keys($stateList);
        echo '  <div>', "\n",
            '   <label for="state">State:</label>', "\n",
            '   <select name="state" id="state" style="width:181px;">', "\n";
        foreach ($keys as $state) {
            if ($this->_event->state == $state) {
                echo '    <option value="', $state, '" selected="selected">';
            } else {
                echo '    <option value="', $state, '">';
            }
            
            echo $stateList[$state], '</option>', "\n";
        }
        echo '   </select>', "\n",
            '  </div>', "\n";
    }

    /**
     * Function for printing the Country form field.
     *
     * @access private
     * @return null
     */
    private function _printCountryField()
    {
        echo '  <div>', "\n",
            '   <label for="country">Country:</label>', "\n",
            '   <select name="country" id="country" style="width:181px;">',
            "\n";
        
        foreach ($this->db->getCountries() as $country) {
            if ($this->_event->country == $country['id']) {
                echo '    <option value="', $country['id'],
                    '" selected="selected">';
            } else {
                echo '    <option value="', $country['id'], '">';
            }

            echo $country['name'], '</option>', "\n";
        }
        echo '   </select>', "\n",
            '  </div>', "\n";
    }
    
    /**
     * Function to print the Edit event form.
     *
     * @access private
     * @return null
     */
    private function _printEditEventForm()
    {
        if ($this->error != '') {
            printError($this->error, 1);
        }
        
        echo ' <form id="newevent" method="post">', "\n",
            '  <h2>Basic Information</h2>', "\n";
        $this->_printFormField(
            'name', 'event name', 'text', L_STORENAME, $this->_event->name
        );
        $this->_printFormField(
            'description', 'Description', 'text', null, $this->_event->description
        );
        $this->_printFormField(
            'address', 'Address', 'text', L_STOREADDR, $this->_event->address
        );
        $this->_printFormField(
            'city', 'City', 'text', L_STOREADDR, $this->_event->city
        );
        $this->_printStates();
        $this->_printFormField(
            'eventzip', 'Zip Code', 'text', L_ZIP, $this->_event->zip->zip
        );
        $this->_printCountryField();
        
        echo '  <div>', "\n",
            '   <label for="description">Start Date/Time:</label>', "\n",
            '   <input id="starttime" name="starttime" type="text" ',
            'maxlength="" value="',
            strftime('%m/%d/%Y %I:%M%p', $this->_event->startTime), '" />', "\n",
            '  </div>', "\n";

        echo '  <div>', "\n",
            '   <label for="description">End Date/Time:</label>', "\n",
            '   <input id="endtime" name="endtime" type="text" ',
            'maxlength="" value="',
            strftime('%m/%d/%Y %I:%M%p', $this->_event->endTime), '" />', "\n",
            '  </div>', "\n";
        
        echo '  <div>', "\n",
            '   <input type="submit" value="Update Event"',
            ' class="button" />', "\n",
            '  </div>', "\n",
            ' </form>', "\n",
            ' <h2>Delete Event</h2>', "\n",
            ' <p class="centered">', "\n",
            '  <a href="?action=delete" onclick="return',
            ' confirm(\'Are you sure you wish to delete this event?\');">',
            'Delete Event</a>', "\n",
            ' </p>', "\n",
            ' <script type="text/javascript"',
            ' src="../scripts/neweventfocus.js">',
            '</script>', "\n";
    }
    
    /**
     * Function to update a event.
     *
     * @access private
     * @return null
     */
    private function _updateEventAction()
    {
        $name    = valueOf($_POST, 'name');
        $desc    = valueOf($_POST, 'description');
        $addr    = valueOf($_POST, 'address');
        $city    = valueOf($_POST, 'city');
        $state   = valueOf($_POST, 'state');
        $zip     = valueOf($_POST, 'eventzip');
        $country = valueOf($_POST, 'country');
        $start   = valueOf($_POST, 'starttime');
        $end     = valueOf($_POST, 'endtime');

        /** Validate/convert starttime, using both old and new error values. */
        $start = strtotime($start);
        if ($start === false || $start === -1) {
            if ($start <= time()) {
                $this->error = 'The Start Date/Time is not valid.';
                return false;
            }
        }

        /** Validate/convert endtime, using both old and new error values. */
        $end = strtotime($end);
        if ($end === false || $end === -1) {
            if ($end <= time()) {
                $this->error = 'The End Date/Time is not valid.';
                return false;
            }
        }
        
        /** Verify ZIP code. */
        if (strlen($zip) > L_ZIP) {
            $this->error = 'The Zip Code you provided is not valid.';
            return false;
        }
        $zip = $this->db->getZipByZip($zip);
        if (!$zip) {
            $this->error = 'The Zip Code you provided is not valid.';
            return false;
        }
        
        /** Get name of country ID. */
        $countries     = $this->db->getCountries();
        $countryLookup = "United States";
        foreach ($countries as $ctry) {
            if ($ctry['id'] == $country) {
                $countryLookup = $ctry['name'];
                break;
            }
        }
        
        /** Geocode address into Lat/Long pair. */
        $request_url = GM_GEOCODE_URL. '&q=' . urlencode(
            $addr . ' ' . $city . ',' . $state . ' ' . $zip->zip . ' '
            . $countryLookup
        );
        $xml         = simplexml_load_file($request_url)
            or trigger_error('Failed to call Geocode API', E_USER_ERROR);
        $status      = $xml->Response->Status->code;
        if ($status == '200') {
            /** Format: Longitude, Latitude, Altitude */
            $coordinates = split(
                ",", $xml->Response->Placemark->Point->coordinates
            );
        } else {
            trigger_error('Geocode API status error: ' .$status, E_USER_ERROR);
        }

        /** Add Event to database. */
        $event = new Event(
            $this->_event->id, $name, $desc, '', $start, $end, $addr,
            $city, $state, $zip, $country, $coordinates[1], $coordinates[0], '',
            $this->_event->distance, $this->_event->stores
        );

        $this->db->deleteEvent($this->_event);
        $result = $this->db->createEvent($this->user, $event);
        if ($result !== true) {
            $this->error = $result;
            return false;
        }
        
        $this->_event = $event;
        return true;
    }
    
    /**
     * Function to display the page.
     *
     * @access public
     * @return null
     */
    public function display()
    {
        if ($this->_event != null
            && ($this->db->isEventOwner($this->user->id, $this->_event)
            || $this->user->role == R_ADMIN)
            && $this->_updateInfo
        ) {
            $this->_updateEventAction();
        }
        
        parent::printHeader();
        if ($this->user->role == R_GUEST) {
            echo 'Please <a title="Click to login" href="',
            RELATIVE_PATH, 'login.php">login</a> first.';
        
        } else if ($this->_event != null
            && ($this->db->isEventOwner($this->user->id, $this->_event)
            || $this->user->role == R_ADMIN)
            && $this->_delete
        ) {
            $this->db->deleteEvent($this->_event);
            echo 'Event deleted.';
            
        } else if ($this->_event != null
            && ($this->db->isEventOwner($this->user->id, $this->_event)
            || $this->user->role == R_ADMIN)
        ) {
            $this->_printEditEventForm();

        } else {
            echo 'Valid event not selected.';
        }
        parent::printFooter();
    }
}

?>